package models

import "gorm.io/gorm"

type News struct {
	gorm.Model
	UserId  int    `gorm:"not null;unique_index"`
	Title   string `gorm:"type:varchar(100);not null;index;comment:'标题'"`
	Content string `gorm:"type:text;not null;comment:'内容'"`
	TypeID  int    `gorm:"type:int;not null;comment:'类型id'"`
	Cover   string `gorm:"type:varchar(255);not null"`
	Remark  string `gorm:"type:varchar(255);not null"`
}
type NewsType struct {
	gorm.Model
	Name string `gorm:"type:varchar(100);not null;index;comment:'名称'"`
}

func (n *News) Update() error {
	return DB.Updates(&n).Error
}

func (n *News) GetNewByID() error {
	return DB.Where("id = ?", n.ID).Limit(1).Find(&n).Error
}
func (u *News) Create() error {
	return DB.Create(&u).Error
}
func (u *News) List(keyword string, page, pageSize, typeId int) (list []*News, err error) {
	db := DB
	if typeId > 0 {
		db = db.Where("type_id = ?", typeId)
	}
	err = DB.Where("title like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
func (u *News) Del() error {
	return DB.Delete(&u).Error
}
